<template>
  <div id="name-modify-box">
    <el-form :model="formModel" label-width="100px" :rules="formRules" ref="form" status-icon>
      <el-form-item label="用户名">
        <span>{{ currentUser.userName }}</span>
      </el-form-item>
      <el-form-item label="修改为" prop="userName">
        <el-input placeholder="请输入用户名" v-model="formModel.userName"/>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="submit">确认</el-button>
        <el-button type="primary" @click="cancel">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import {mapState} from "vuex";
import {commonMixin} from "@/mixin";

export default {
  name: "UsernameModify",
  data() {
    return {
      formModel: {
        userName: '',
      },
      formRules: {
        userName: [
          {max: 12, message: '长度不能超过 12 个字符', trigger: 'blur'},
        ],
      }
    }
  },
  mixins: [commonMixin],
  computed: {
    ...mapState(['currentUser']),
  },
  methods: {
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const url = '/users/username';
          const user = this.currentUser;
          user.userName = this.formModel.userName;
          this.axios.put(url, user).then(resp => {
            // 响应成功
            if (resp.code === 200) {
              this.$message({
                type: "success",
                message: '修改成功',
                showClose: true,
                center: true,
              });
              // 更新currentUser
              this.updateLocalStorageUser(resp.data);
            } else {
              // 响应失败
              this.$message({
                type: "error",
                message: '修改失败',
                showClose: true,
                center: true,
              })
            }
          })
        } else {
          console.log('输入有误，请检查！');
          return false;
        }
      })
    },
    cancel() {
      this.$router.go(-1);
    }
  },
}
</script>

<style scoped>

#name-modify-box {
  display: flex;
  justify-content: space-between;
}

</style>